home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8512 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Problem Negating an Unsigned Char
  5. Date: 4 Mar 1996 11:18:08 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4hfflgINNd9v@keats.ugrad.cs.ubc.ca>
  8. References: <Dnnros.Lq.0.-s@hkusuc.hku.hk> <4he27sINNdel@keats.ugrad.cs.ubc.ca> <4he5f0$acv@solutions.solon.com>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <4he5f0$acv@solutions.solon.com>,
  12. Peter Seebach <seebs@solutions.solon.com> wrote:
  13.  >In article <4he27sINNdel@keats.ugrad.cs.ubc.ca>,
  14.  >Kazimir Kylheku <c2a192@ugrad.cs.ubc.ca> wrote:
  15.  >>To make it portable, you must manually mask for the lower eight bits:
  16.  >
  17.  >>    if (a == (~b & 0xff))
  18.  >
  19.  >Close, but the cigar yet escapes you.
  20.  
  21. I don't think so.
  22.  
  23.  >    if (a == (~b & ((1 << CHAR_BIT) - 1)))
  24.  
  25. I assumed that the poster is interested in manipulating eight bit bytes, which
  26. he defines using two digit hexadecimal constants.  I know that he wants only
  27. eight bits, because his program suggests that he expects 0x11 to be the
  28. complement of 0xEE.
  29.  
  30. The char datatype is guaranteed to hold eight bits, thus my masking is valid
  31. and portable. He did not say that he wants to utilize the full,
  32. machine-specific precision of the unsigned char datatype, and is in fact
  33. probably oblivious to the fact that chars can hold more than eight bits.
  34.  
  35.  >Further, you can't do this portably; if sizeof(long) is 1, the
  36.  >shift is illegal.
  37.  
  38. It's your shift, not mine. If you want to use the full precision, all you have
  39. to do is invert and cast through unsigned char.
  40.  
  41.     if (a == (unsigned char) ~b) 
  42.  
  43. b gets promoted to unsigned int, and then is inverted. The cast to unsigned
  44. char truncates it down to CHAR_BITS precision. It's then promoted again to
  45. unsigned int. Effectively, you have inverted just the bits that belonged to the
  46. original unsigned char value of b.
  47.  
  48. The poster did say that this works for him, but he is not aware that it is not
  49. the portable eight bit arithmetic that he wants. It just so happens that on his
  50. implementation, a char is eight bits, so the complement of 0xEE is the 0x11
  51. that he expects, rather than 0x111 (9 bit char), 0x311 (10 bit char) and so
  52. forth.
  53. -- 
  54.  
  55.